/**
 * Created by sun on 2015/3/12.
 */
package com.jbm.core.common;

import com.google.protobuf.GeneratedMessage;
import com.jbm.core.iface.IAcross;
import com.jbm.core.pb.PBIAcross;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import javax.persistence.criteria.CriteriaBuilder;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class OHEncoder extends ProtocolEncoderAdapter
{
	private final String charset;

	public OHEncoder(String charset)
	{
		this.charset = charset;
	}

	public void encode(IoSession session, Object message,
	                   ProtocolEncoderOutput out) throws Exception
	{

		int protoc_type = Integer.parseInt((String) session.getAttribute("PROTOC_TYPE"));

		if (protoc_type == 0)
		{
			IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
			PBIAcross.IAcross pbresponse = (PBIAcross.IAcross)message;

			Object from = new TransClass().PB2_0toI1_0(pbresponse);

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(from);
			byte[] bytes = baos.toByteArray();

			buf.putInt(bytes.length & 0x0FFFFFFF);
			buf.put(bytes);
			buf.flip();

			out.write(buf);
		} else if (protoc_type == 0x10)
		{
			IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
			PBIAcross.IAcross pbresponse = (PBIAcross.IAcross)message;

			String cname = message.getClass().getSimpleName();

			int len = 2;

			byte[] bytes;
			byte[] bname = cname.getBytes("UTF8");

			len += bname.length;

			GeneratedMessage pb = (GeneratedMessage) new TransClass().PB2_0toPB1_0(pbresponse);
			bytes = pb.toByteArray();

			len += bytes.length;

			len = ((len & 0x0FFFFFFF) | (protoc_type << 24));
			buf.putInt(len);
			buf.putShort((short) cname.length());
			buf.put(bname);
			buf.put(bytes);
			buf.flip();

			out.write(buf);
		} else if (protoc_type == 0x20)
		{
			IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);

			if ( message instanceof OHByte )
			{
				byte[] bytes = ((OHByte)message).buffer;
				short index = (short)(((OHByte)message).pbia.getQindex()&0x7ffff);
				byte[] slen = new byte[2];

				int len = bytes.length;
				buf.put((byte)(0x21&0xff));
				buf.put((byte)((len>>8)&0xff));
				buf.put((byte)(len&0xff));
				buf.put((byte)((index>>8)&0xff));
				buf.put((byte)(index&0xff));
				buf.put(bytes);
				buf.flip();

				out.write(buf);
			}else
			{
				PBIAcross.IAcross pbresponse = (PBIAcross.IAcross) message;

				byte[] bytes = pbresponse.toByteArray();
				int len = bytes.length;
				len = ((len & 0x00FFFFFF) | (protoc_type << 24));
				buf.putInt(len);
				buf.put(bytes);
				buf.flip();

				out.write(buf);
			}
		}
	}
}
